<template>
  <div class="ssc-list org-person-list">
    <div class="org">
      <div class="org-title"
        >分类管理<span><sync-outlined @click="resetGroup" /><plus-circle-outlined @click="addCategory(serviceUuid, '0')" /></span
      ></div>
      <a-tree :defaultExpandAll="true" :tree-data="treeData" @select="selectNode">
        <template #title="{ name, serviceUuid, sort, uuid }">
          <a-dropdown :trigger="['contextmenu']">
            <span>{{ name }}</span>
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="() => addCategory(serviceUuid, uuid, sort, name)">添加下级</a-menu-item>
                <a-menu-item key="2" @click="() => editCategory(uuid, name)">编辑</a-menu-item>
                <a-menu-item key="3" style="color: red">
                  <a-popconfirm placement="bottom" ok-text="确定" cancel-text="取消" @confirm="delCategory(uuid)">
                    <template #title>
                      <p>删除确认</p>
                      <p class="w-[200px]">删除后无法恢复，确定要删除吗？</p>
                    </template>
                    <span class="del" href="javascript:;">删除</span>
                  </a-popconfirm>
                </a-menu-item>

                <!-- <a-menu-item key="3">上/下</a-menu-item> -->
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </a-tree>
    </div>
    <div class="content">
      <div class="ssc-table">
        <div class="ssc-table-header">
          <span class="ssc-table-header-title">接口管理</span>
          <a-button type="primary" @click="add()">
            <template #icon><plus-outlined :style="{ 'font-weight': 'bold' }" /></template>
            添加接口
          </a-button>
        </div>
        <a-table :columns="table.columns" :data-source="dataList" :loading="loading" :pagination="false">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <span>
                <a @click="edit(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm placement="bottom" ok-text="确定" cancel-text="取消" @confirm="del(record)">
                  <template #title>
                    <p>删除确认</p>
                    <p class="w-[200px]">删除后无法恢复，确定要删除吗？</p>
                  </template>
                  <span class="del" href="javascript:;">删除</span>
                </a-popconfirm>
                <a-divider type="vertical" />
                <a-popconfirm placement="bottom" ok-text="确定" cancel-text="取消" @confirm="update(record)">
                  <template #title>
                    <p>{{ record.state === 0 ? '上架' : '下架' }}确认</p>
                    <p class="w-[200px]">{{ record.state === 0 ? '上架后接口将可以使用' : '下架后接口将无法使用' }}，确定要{{ record.state === 0 ? '上架' : '下架' }}吗？</p>
                  </template>
                  <span :class="record.state === 0 ? 'up' : 'down'" href="javascript:;">{{ record.state === 0 ? '上架' : '下架' }}</span>
                </a-popconfirm>
              </span>
            </template>
          </template>
        </a-table>
      </div>
    </div>
    <div class="modal">
      <AddCategory v-model:visible="modalAddCategory.visible" :data="modalAddCategory.data" @success="modalAddCategory.success" />
      <EditCategory v-model:visible="modalEditCategory.visible" :data="modalEditCategory.data" @success="modalEditCategory.success" />
      <Add v-model:visible="modalAdd.visible" @success="modalAdd.success" />
      <Edit v-model:visible="modalEdit.visible" :data="modalEdit.data" @success="modalEdit.success" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { PlusCircleOutlined, PlusOutlined, SyncOutlined } from '@ant-design/icons-vue'
  import { onMounted, reactive, ref } from 'vue'
  import { useRoute } from 'vue-router'

  import { requestDeleteGroup, requestRecursionGroupTree } from '/@/api/manage/openApiGroup'
  import { requestApiList, requestDeleteApi, requestUpdateApiState } from '/@/api/manage/openApiInterface'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  import Add from './components/Add.vue'
  import AddCategory from './components/AddCategory.vue'
  import Edit from './components/Edit.vue'
  import EditCategory from './components/EditCategory.vue'
  const route = useRoute()
  const serviceUuid = route.query.serviceUuid as string
  const treeData = ref([])
  const groupUuid = ref() // 选择节点的分组id

  /** 递归查询分组树 */
  const recursionGroupTree = async () => {
    const { responseCode, responseData } = await requestRecursionGroupTree({ serviceUuid })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      treeData.value = responseData
    }
  }
  recursionGroupTree()

  onMounted(() => queryList())
  let result = ''
  const findChildNodes = (element, groupUuid) => {
    element.forEach((node: any) => {
      if (node.uuid === groupUuid) {
        result = node.name
      } else {
        findChildNodes(node.children, groupUuid)
      }
    })
    return result
  }
  /** 表格配置 */
  const table = reactive({
    columns: [
      { title: '接口名称', dataIndex: 'apiName' },
      {
        title: '分组',
        dataIndex: 'groupUuid',
        customRender: ({ record }) => {
          return findChildNodes(treeData.value, record.groupUuid)
        },
      },
      // { title: '域名', dataIndex: 'hostDomain' },
      {
        title: 'URL',
        dataIndex: 'path',
        customRender: ({ record }) => {
          return `${record.path}`
        },
      },
      {
        title: '请求方法',
        key: 'method',
        dataIndex: 'method',
      },
      { title: '操作', key: 'action' },
    ],
  })
  const dataList = ref([])
  const loading = ref(false)
  const queryList = async () => {
    loading.value = true
    const { responseCode, responseData } = await requestApiList({ serviceUuid, groupUuid: groupUuid.value })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      dataList.value = responseData
    }
    loading.value = false
  }
  queryList()

  /** 新增弹窗 */
  const modalAdd = reactive({
    visible: false,
    success: () => queryList(),
  })
  /**
   * 新增
   */
  const add = () => {
    modalAdd.visible = true
  }

  /** 新增分组弹窗 */
  const modalAddCategory = reactive({
    visible: false,
    data: {},
    success: () => recursionGroupTree(),
  })
  const addCategory = (serviceUuid = '', uuid = '', sort = '', name = '') => {
    modalAddCategory.visible = true
    modalAddCategory.data = {
      serviceUuid,
      parentUuid: uuid,
      sort,
      name,
    }
    console.log({ serviceUuid, uuid, sort, name })
  }

  const resetGroup = () => {
    groupUuid.value = ''
    queryList()
  }

  /** 编辑分组弹窗 */
  const modalEditCategory = reactive({
    visible: false,
    data: {},
    success: () => recursionGroupTree(),
  })
  const editCategory = (uuid: string, name: string) => {
    modalEditCategory.data = {
      uuid,
      name,
    }
    modalEditCategory.visible = true
  }

  const delCategory = async (uuid: string) => {
    const { responseCode } = await requestDeleteGroup({ uuid })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      recursionGroupTree()
    }
  }

  const selectNode = (selectedKeys, e) => {
    console.log({ selectedKeys, e })
    groupUuid.value = e.node.uuid
    queryList()
  }

  /** 编辑弹窗 */
  const modalEdit = reactive({
    visible: false,
    data: {},
    success: () => queryList(),
  })

  /**
   * 编辑
   */
  const edit = (record) => {
    modalEdit.data = record
    modalEdit.visible = true
  }
  // 删除接口
  const del = async (record) => {
    const { responseCode } = await requestDeleteApi({ uuid: record.uuid })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      queryList()
    }
  }
  // 上下架接口
  const update = async (record) => {
    const { responseCode } = await requestUpdateApiState({ uuid: record.uuid, state: record.state === 1 ? 0 : 1 })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      queryList()
    }
  }
</script>

<style lang="less" scoped>
  .org-person-list {
    display: flex;
  }

  .org {
    width: 200px;
    height: 100%;
    padding: 18px;
    background: #fff;

    .org-title {
      margin-bottom: 12px;
      font-weight: bold;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .anticon-plus-circle,
      .anticon-sync {
        cursor: pointer;
        color: #08979c;
        margin-left: 10px;
      }
    }

    .classification {
      height: 40px;
      width: 100%;
      line-height: 40px;
      padding: 0 4px;
      display: flex;
      justify-content: space-between;
      cursor: pointer;

      &:hover {
        background: #cbf4f6;
        color: #08979c;

        .action {
          display: block;
        }
      }

      .action {
        display: none;
        color: #08979c;
        font-size: 12px;

        > span {
          margin-left: 4px;
        }
      }
    }
  }

  .del {
    color: #f5222d;
  }

  .down {
    color: #f5222d;
    cursor: pointer;
  }

  .up {
    color: #08979c;
    cursor: pointer;
  }

  .content {
    flex: 1;
  }

  .ssc-table {
    margin-left: 16px;
    margin-top: 0;

    .dept-leader {
      position: relative;
      top: -2px;
      height: 20px;
      margin-right: 4px;
      padding: 0 8px;
      border: none;
      font-size: 10px;
      background: #87d068;
    }
  }
</style>
